<template>
  <div class="student-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" size="small" class="search-form">
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.sname" placeholder="学生关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.cname" placeholder="班级关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-input v-model="searchForm.major" placeholder="专业关键字" style="width:120px;" />
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;margin-right:8px;">
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item style="margin-bottom:0;">
          <el-button type="success" :icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" :loading="tableLoading" border style="width: 100%" size="small">
  <el-table-column type="index" label="序号" width="60" align="center" />
  <el-table-column prop="student_number" label="学号" width="160" />
  <el-table-column prop="student_name" label="姓名" width="120" />
  <el-table-column prop="class_name" label="班级" show-overflow-tooltip />
  <el-table-column prop="major_name" label="专业名" show-overflow-tooltip />
        <el-table-column prop="student_sex" label="性别" width="80" align="center">
          <template #default="{ row }">
            <span class="badge" :class="row.student_sex === 1 ? 'badge--blue' : 'badge--red'">
              {{ row.student_sex === 1 ? '男' : '女' }}
            </span>
          </template>
        </el-table-column>
  <el-table-column prop="student_last_login_time" label="最后一次登录时间" />
  <el-table-column label="操作" fixed="right" width="160">
          <template #default="{ row }">
            <div style="display: flex; justify-content: space-around">
              <el-button size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" :icon="DeleteIcon" @click="handleDelete(row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.pageNo"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          size="small"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" class="form-dialog" modal-class="light-modal-mask">
      <el-form :model="dialogForm" label-width="120px" size="small">
        <el-form-item label="学号/手机号">
          <el-input v-model="dialogForm.student_number"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="dialogForm.student_name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="dialogForm.student_email"></el-input>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker
            v-model="dialogForm.student_birthday"
            type="date"
            placeholder="选择日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="dialogForm.student_sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属班级">
          <el-select v-model="dialogForm.student_class_id" placeholder="请选择班级">
            <el-option
              v-for="item in classList"
              :key="item.class_id"
              :label="item.class_name"
              :value="item.class_id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button size="small" @click="dialogVisible = false">取消</el-button>
          <el-button size="small" type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <BaseConfirmDialog
      :visible="confirmVisible"
      title="提示"
      :message="confirmMessage"
      confirm-text="确定"
      cancel-text="取消"
      @confirm="confirmDelete"
      @cancel="confirmVisible=false"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  getStudentAPI,
  addStudentAPI,
  updateStudentAPI,
  deleteStudentAPI
} from '@/api/admin/student.js'
import { getClassAPI } from '@/api/admin/class.js'
import BaseConfirmDialog from '@/components/BaseConfirmDialog.vue'
import { Search, Refresh, Plus, Edit, Delete as DeleteIcon } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  sname: '',
  cname: '',
  major: ''
})

// 表格数据
const tableData = ref([])
const tableLoading = ref(false)

// 分页
const pagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogForm = reactive({
  student_id: '',
  student_number: '',
  student_name: '',
  student_email: '',
  student_birthday: '',
  student_sex: 1,
  student_class_id: ''
})
const isEdit = ref(false)

// 班级下拉列表
const classList = ref([])

// 获取学生数据
const fetchStudents = async () => {
  const params = {
    pageNo: pagination.pageNo,
    pageSize: pagination.pageSize,
    ...searchForm
  }
  tableLoading.value = true
  try {
    const res = await getStudentAPI(params)
    // 拦截器已返回 data 字段
    tableData.value = res?.list || []
    pagination.total = res?.total || 0
  } finally {
    tableLoading.value = false
  }
}

// 获取班级数据
const fetchClasses = async () => {
  const res = await getClassAPI({ pageNo: 1, pageSize: 999 }) // 获取所有班级
  classList.value = res?.list || []
}

onMounted(() => {
  fetchStudents()
  fetchClasses()
})

// 搜索
const handleSearch = () => {
  pagination.pageNo = 1
  fetchStudents()
}

// 重置
const handleReset = () => {
  searchForm.sname = ''
  searchForm.cname = ''
  searchForm.major = ''
  pagination.pageNo = 1
  fetchStudents()
}

// 添加
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加学生'
  Object.assign(dialogForm, {
    student_id: '',
    student_number: '',
    student_name: '',
    student_email: '',
    student_birthday: '',
    student_sex: 1,
    student_class_id: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑学生'
  Object.assign(dialogForm, {
    student_id: row.student_id,
    student_number: row.student_number,
    student_name: row.student_name,
    student_email: row.student_email,
    student_birthday: row.student_birthday,
    student_sex: row.student_sex,
    student_class_id: row.class_id
  })
  dialogVisible.value = true
}

// 删除
const confirmVisible = ref(false)
const confirmMessage = ref('')
let pendingDeleteId = ''
const handleDelete = (row) => {
  pendingDeleteId = row.student_id
  confirmMessage.value = `确定要删除学生 "${row.student_name}" 吗？`
  confirmVisible.value = true
}
const confirmDelete = async () => {
  await deleteStudentAPI({ student_id: pendingDeleteId })
  confirmVisible.value = false
  fetchStudents()
}

// 提交表单
const handleSubmit = async () => {
  let res
  if (isEdit.value) {
    // 编辑
    res = await updateStudentAPI(dialogForm)
  } else {
    // 添加
    res = await addStudentAPI(dialogForm)
  }
  // 成功消息已由响应拦截器统一处理
  dialogVisible.value = false
  fetchStudents()
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchStudents()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.pageNo = val
  fetchStudents()
}
</script>

<style lang="scss" scoped>
.student-container {
  padding: 8px 20px 20px 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-bar {
  display: flex;
  align-items: center;
  padding: 0;
  margin: 0 0 18px 0;
  background: none;
  border: none;
  box-shadow: none;
}
.search-form {
  display: flex;
  align-items: center;
  gap: 0;
  padding: 0;
  margin: 0;
}
.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 8px;
}
.search-form .el-input__wrapper,
.search-form .el-button {
  height: 26px !important;
  min-height: 26px !important;
  font-size: 13px;
}
.table-card {
  margin-top: 0;
}
.el-table {
  margin-top: 0;
}
.el-pagination {
  margin-top: 6px;
  display: flex;
  justify-content: flex-start;
}
.el-pagination .el-pager li {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  background: #fff;
  color: #606266;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
  margin: 0 2px;
  font-size: 15px;
  cursor: pointer;
}
.el-pagination .el-pager li.active {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
}
.table-card {
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding-top: 6px;
}
.table-card :deep(.el-card__body) {
  flex: 1 1 0%;
  min-height: 0;
  display: flex;
  flex-direction: column;
}
.table-card :deep(.el-table) {
  flex: 1 1 auto;
  overflow: auto;
}
.pagination {
  margin-top: 8px;
  display: flex;
  justify-content: center;
}
</style>
